package org.elephas.webapp.model;

import org.apache.wicket.injection.web.InjectorHolder;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.elephas.model.Post;
import org.elephas.service.PostFinder;

/**
 * Detachable model that either loads the specified {@link Post} or creates a
 * new one on the fly.
 * 
 * @author Gerolf Seitz
 * 
 */
public class DetachablePostModel extends LoadableDetachableModel<Post> {

	private static final long serialVersionUID = 1L;

	@SpringBean
	private PostFinder service;

	private String postId = null;

	/**
	 * Use this constructor in Post forms for creating new posts.
	 */
	public DetachablePostModel() {
		InjectorHolder.getInjector().inject(this);
	}

	/**
	 * Use this constructor in Post forms for editing existing posts.
	 * 
	 * @param post
	 */
	public DetachablePostModel(Post post) {
		this();
		if (post != null) {
			postId = post.getUuid();
		}
	}

	public DetachablePostModel(String uuid) {
		this();
		postId = uuid;
	}

	@Override
	protected Post load() {
		if (postId == null) {
			return new Post();
		}
		return service.findById(postId);
	}
}
